<template>
  <div class="map-picker">
    <van-dialog
      v-model:show="showMapDialog"
      title="选择位置"
      :width="375"
      confirm-button-text="确认"
      cancel-button-text="取消"
      @confirm="handleConfirm"
    >
      <div class="map-container">
        <div class="map-wrapper">
          <div id="map-container" ref="mapContainer"></div>
          <div class="search-box">
            <input
              v-model="searchKeyword"
              placeholder="输入地点进行搜索"
              @input="handleSearchSuggest"
            />
            <ul v-if="suggestions.length" class="suggest-list">
              <li v-for="item in suggestions" :key="item.id" @click="selectLocation(item)">
                {{ item.name }} - {{ item.address }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader'
import { showToast } from 'vant'
import { useLocationStore } from '@/stores/locationStore'
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ lng: 116.397428, lat: 39.90923 }) // 默认北京坐标
  }
})

const emit = defineEmits(['update:modelValue'])
const router = useRouter()
const locationStore = useLocationStore()
const mapContainer = ref(null)
const map = ref(null)
const marker = ref(null)
const searchKeyword = ref('')
const suggestions = ref([])
const amapInstance = ref(null)
const showMapDialog = ref(true)
const selectedLocation = ref(null)
//  初始化地图
const setupMap = async () => {
  console.log(import.meta.env.VITE_AMAP_KEY)
  try {
    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY, // 在.env文件中配置
      version: '2.0',
      plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
    })

    map.value = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center: [props.modelValue.lng, props.modelValue.lat]
    })

    // 添加点击事件
    map.value.on('click', (e) => {
      console.log(e)
      updatePosition(e.lnglat)
    })

    // 初始化标记
    marker.value = new AMap.Marker({
      position: map.value.getCenter(),
      map: map.value
    })

    // 保存AMap实例
    amapInstance.value = AMap
  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 更新位置
const updatePosition = (lnglat) => {
  marker.value.setPosition(lnglat)
  map.value.setCenter(lnglat)

  // 使用逆地理编码获取详细地址信息和 districtCode
  const geocoder = new amapInstance.value.Geocoder({
    extensions: 'all' // 获取详细信息
  })

  geocoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      const addressComponent = result.regeocode.addressComponent
      console.log('addressComponent', addressComponent)
      selectedLocation.value = {
        lng: lnglat.getLng(),
        lat: lnglat.getLat(),
        address: result.regeocode.formattedAddress,
        districtCode: addressComponent.adcode
      }
      emit('update:modelValue', selectedLocation.value)
      locationStore.setLocation(selectedLocation.value)
    } else {
      console.error('逆地理编码失败:', result)
      showToast('获取地址信息失败，请重试')
    }
  })
}

// 地点搜索建议
const handleSearchSuggest = async () => {
  if (!searchKeyword.value.trim()) {
    suggestions.value = []
    return
  }

  if (!amapInstance.value) return

  const autoComplete = new amapInstance.value.AutoComplete({
    city: '全国'
  })

  autoComplete.search(searchKeyword.value, (status, result) => {
    console.log(111111, status, result)
    if (status === 'complete' && result.info === 'OK') {
      console.log(2222)
      suggestions.value = result.tips.filter((item) => item.location)
    }
  })
}

// 选择建议项
const selectLocation = (item) => {
  searchKeyword.value = item.name
  suggestions.value = []
  const lnglat = new amapInstance.value.LngLat(item.location.lng, item.location.lat)
  updatePosition(lnglat)
}
// 确认选择
const handleConfirm = () => {
  if (selectedLocation.value) {
    emit('update:modelValue', selectedLocation.value)
    console.log(selectedLocation.value)
    router.go(-1)
  } else {
    showToast('请选择一个位置')
    showMapDialog.value = true
  }
}

onMounted(() => {
  setupMap()
})
// 监听坐标变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (map.value) {
      const center = new amapInstance.value.LngLat(newVal.lng, newVal.lat)
      map.value.setCenter(center)
      marker.value.setPosition(center)
    }
  }
)
</script>

<style scoped>
.map-container {
  width: 375px;
  height: 70vh;
  position: relative;
}
.map-wrapper {
  width: 375px;
  height: 70vh;
}
#map-container {
  width: 100%;
  height: 100%;
}

.search-box {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

input {
  width: 250px;
  padding: 8px;
  border: 1px solid #ddd;
}

.suggest-list {
  list-style: none;
  padding: 0;
  margin-top: 5px;
  max-height: 200px;
  overflow-y: auto;
  width: 300px;
}

.suggest-list li {
  padding: 8px;
  cursor: pointer;
  transition: background 0.3s;
  font-size: 14px;
}

.suggest-list li:hover {
  background: #f5f5f5;
}
</style>
